<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="80px"
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        label="公告标题"
        prop="title"
      >
        <el-input v-model="dataForm.title" class="custom-input-width" />
      </el-form-item>
      <el-form-item
        label="状态"
        prop="status"
      >
        <el-radio-group v-model="dataForm.status">
          <el-radio :value="1">
            公布
          </el-radio>
          <el-radio :value="0">
            撤销
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="置顶"
        prop="isTop"
      >
        <el-radio-group v-model="dataForm.isTop">
          <el-radio :value="1">
            是
          </el-radio>
          <el-radio :value="0">
            否
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="公告内容"
        prop="content"
      >
        <div ref="quillContainerRef" class="quill-container"></div>
    
        <el-upload
          class="upload-demo"
          list-type="picture"
          :action="uploadAction"
          :headers="uploadHeaders"
          :on-success="imageSuccessCBK"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
        >
          <el-button
            size="small"
            type="primary"
          >
            点击上传图片
          </el-button>
        </el-upload>
      
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus';
import { Debounce } from '@/utils/debounce';
import Quill from 'quill';

const emit = defineEmits(['refreshDataList']);
const visible = ref(false);
const quillContainerRef = ref(null);

// eslint-disable-next-line no-unused-vars
const validateTitle = (rule, value, callback) => {
  if (!value.trim()) {
    dataForm.value.title = '';
    callback(new Error('公告标题不能为空'));
  } else {
    callback();
  }
};

const dataRule = {
  title: [
    { required: true, message: '公告标题不能为空', trigger: 'blur' },
    { validator: validateTitle, trigger: 'blur' },
  ],
};

const dataForm = ref({
  title: null,
  content: null,
  url: null,
  status: 1,
  isTop: 0,
});
const dataFormRef = ref(null);

let quillInstance; // 声明公共的 Quill 实例变量

const init = (id) => {
       dataForm.value.id = id || 0;
       visible.value = true;
       nextTick(() => {
           dataFormRef.value?.resetFields();
           if (dataForm.value.id) {
               // 有 id，加载已有数据并初始化 Quill（现有逻辑）
               http({
                   url: http.adornUrl('/shop/notice/info/' + dataForm.value.id),
                   method: 'get',
                   params: http.adornParams(),
               })
              .then(({ data }) => {
                   dataForm.value = data;
                   if (dataForm.value.content) {
                       if (!quillInstance) {
                           quillInstance = new Quill(quillContainerRef.value, {
                               placeholder: '开始你的编写',
                               theme: 'snow',
                               readOnly: false,
                           });
                       }
                       quillInstance.root.innerHTML = dataForm.value.content;
                   }
               });
           } else {
               // 没有 id，新增场景，创建 Quill 实例
               if (!quillInstance) {
                   quillInstance = new Quill(quillContainerRef.value, {
                       placeholder: '开始你的编写',
                       theme: 'snow',
                       readOnly: false,
                   });
               }
           }
       });
   };
defineExpose({ init });

const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (!quillInstance) {
        quillInstance = new Quill(quillContainerRef.value, {
          theme: 'snow',
          readOnly: false,
        });
      }
      const content = quillInstance.root.innerHTML;
      dataForm.value.content = content;
      http({
        url: http.adornUrl('/shop/notice'),
        method: dataForm.value.id? 'put' : 'post',
        data: http.adornData(dataForm.value),
      })
      .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              visible.value = false;
              emit('refreshDataList');
              dataForm.value.content = '';
            },
          });
        });
    }
  });
});

// 上传文件
const uploadAction = http.adornUrl('/admin/upload');
const resourcesUrl = import.meta.env.VITE_APP_BASE_API;
const imageSuccessCBK = (response, file, fileList) => {
  if (!quillInstance) {
    quillInstance = new Quill(quillContainerRef.value, {
      theme: 'snow',
      readOnly: false,
    });
  }
  quillInstance.insertEmbed(quillInstance.getLength(), 'image', `${resourcesUrl + "/admin-file/" + file.response.data}`);
};
</script>

<style>
.custom-input-width.el-input__inner {
  width: 500px; /* 根据实际需求调整宽度 */
}
.quill-container {
  width: 370px;
}
</style>